# uncompyle6 version 2.11.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.9 (default, Sep 17 2016, 20:26:04) 
# [GCC 4.9.2]
# Embedded file name: D:\project\inleader_frist_client\print_client\core\wifi_api.py
# Compiled at: 2013-12-30 03:11:06
import dbus.mainloop.glib
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
from setting import setting
import json
import uuid
import time
import commands
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
import NetworkManager

class WifiApi(QObject):

    def __init__(self):
        QObject.__init__(self)
        NetworkManager.NetworkManager.connect_to_signal('StateChanged', self.networkStateChange)
        self.signal = WifiSignal()

    def networkStateChange(self, state):
        self.signal.networkStateSignal.emit(state)

    def deviceStateChange(self, new_state, old_state, reason):
        self.signal.deviceStateSignal.emit(new_state, old_state, reason)

    def _get_connection_by_name(self, name):
        connection_list = NetworkManager.Settings.ListConnections()
        for connection in connection_list:
            setting = connection.GetSettings()
            if setting['connection']['id'] == name:
                return connection

        return None

    def get_wireless_by_name(self, name):
        devices = NetworkManager.NetworkManager.GetDevices()
        for device in devices:
            specif_device = device.SpecificDevice()
            if isinstance(specif_device, NetworkManager.Wireless):
                if device.Interface == name:
                    return device

        return None

    def _get_access_point(self, name):
        device = self.get_wireless_by_name(name)
        specif_device = device.SpecificDevice()
        ap_list = specif_device.GetAccessPoints()
        access_point_list = []
        for ap in ap_list:
            ap_dict = {'ssid': ap.Ssid,'bssid': ap.HwAddress,'strength': ord(ap.Strength),'frequency': ap.Frequency,'wpaFlags': ap.WpaFlags,'rsnFlags': ap.RsnFlags}
            access_point_list.append(ap_dict)

        return access_point_list

    @pyqtSlot(str)
    def connection_device_state(self, name):
        device = self.get_wireless_by_name(name)
        device.connect_to_signal('StateChanged', self.deviceStateChange)

    @pyqtSlot(result=str)
    def get_wireless_device(self):
        devices = NetworkManager.NetworkManager.GetDevices()
        device_list = []
        for device in devices:
            specif_device = device.SpecificDevice()
            if isinstance(specif_device, NetworkManager.Wireless):
                connection = {'status': u'\u5df2\u65ad\u5f00','ssid': '','bssid': '','ipAddr': ''}
                if device.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED:
                    active_connection = device.ActiveConnection
                    connection['status'] = u'\u5df2\u8fde\u63a5'
                    ip4config = device.Ip4Config
                    connection['ipAddr'] = ip4config.Addresses[0][0]
                    ap = specif_device.ActiveAccessPoint
                    connection['ssid'] = ap.Ssid
                    connection['bssid'] = ap.HwAddress
                device = {'name': device.Interface,'mac': specif_device.HwAddress,'active_connection': connection}
                device_list.append(device)

        return json.dumps(device_list)

    @pyqtSlot(str, result=str)
    def get_access_point(self, name):
        return json.dumps(self._get_access_point(name))

    @pyqtSlot(str, result=str)
    def get_connection_by_name(self, name):
        connection = self._get_connection_by_name(name)
        if connection is None:
            return json.dumps(None)
        else:
            secrets = {}
            try:
                secrets = connection.GetSecrets()
            except:
                pass

            setting = connection.GetSettings()
            if setting['802-11-wireless-security']['key-mgmt'] == 'none':
                setting['password'] = secrets['802-11-wireless-security']['wep-key0']
            if setting['802-11-wireless-security']['key-mgmt'] == 'wpa-psk':
                setting['password'] = secrets['802-11-wireless-security']['psk']
            return json.dumps(setting)

    @pyqtSlot(str, str)
    def delete_connection(self, name, ssid):
        access_point_list = self._get_access_point(name)
        for ap in access_point_list:
            if ap['ssid'] == ssid:
                connection = self._get_connection_by_name(ssid)
                if connection is not None:
                    connection.Delete()

        return

    @pyqtSlot(str, str, str)
    def connection(self, name, ssid, pwd):
        device = self.get_wireless_by_name(name)
        access_point_list = self._get_access_point(name)
        for ap in access_point_list:
            if ap['ssid'] == ssid:
                wifi_setting = self.get_connection_template(ap['wpaFlags'], ap['rsnFlags'], str(ssid), str(pwd))
                connection = self._get_connection_by_name(ssid)
                if connection is not None:
                    connection.Delete()
                if device.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED:
                    device.Disconnect()
                try:
                    setting.logger.debug(wifi_setting)
                    NetworkManager.NetworkManager.AddAndActivateConnection(wifi_setting, device, '/')
                except Exception as e:
                    print e

                return

        return

    @pyqtSlot(str)
    def disconnect(self, name):
        device = self.get_wireless_by_name(name)
        device.Disconnect()

    def get_connection_template(self, wpaFlags, rsnFlags, ssid, pwd):
        result = {'802-11-wireless': {'mode': 'infrastructure','security': '802-11-wireless-security',
                               'ssid': ssid
                               },
           '802-11-wireless-security': {'auth-alg': 'open','key-mgmt': 'none','wep-key0': pwd},'connection': {'id': ssid,'type': '802-11-wireless',
                          'uuid': str(uuid.uuid4())
                          },
           'ipv4': {'method': 'auto'},'ipv6': {'method': 'auto'}}
        setting.logger.debug('wpaFlags %d RsnFlags %d' % (wpaFlags, rsnFlags))
        if wpaFlags & NetworkManager.NM_802_11_AP_SEC_KEY_MGMT_PSK or rsnFlags & NetworkManager.NM_802_11_AP_SEC_KEY_MGMT_PSK:
            result['802-11-wireless-security']['key-mgmt'] = 'wpa-psk'
            del result['802-11-wireless-security']['wep-key0']
            result['802-11-wireless-security']['psk'] = pwd
        return result

    @pyqtSlot(result=str)
    def show_soft_keyboard(self):
        cmd = '/usr/bin/onboard'
        result = commands.getoutput(cmd)
        setting.logger.debug(result)
        return result


class WifiSignal(QObject):
    networkStateSignal = pyqtSignal(int)
    deviceStateSignal = pyqtSignal(int, int, int)